<template>
  <div class="health-record-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-button 
            type="text" 
            @click="$router.back()" 
            class="back-button"
          >
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <h1>健康档案</h1>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleSave" :loading="saving">
            <el-icon><DocumentAdd /></el-icon>
            保存档案
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 主要内容 -->
    <div class="health-content">
      <div class="content-grid">
        <!-- 基本信息卡片 -->
        <div class="info-card">
          <div class="card-header">
            <h3><el-icon><User /></el-icon>基本信息</h3>
          </div>
          <div class="card-content">
            <el-form :model="healthRecord" label-width="100px" class="health-form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="身高">
                    <el-input-number
                      v-model="healthRecord.height"
                      :min="100"
                      :max="250"
                      :precision="1"
                      controls-position="right"
                      class="full-width"
                    >
                      <template #append>cm</template>
                    </el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="体重">
                    <el-input-number
                      v-model="healthRecord.weight"
                      :min="30"
                      :max="200"
                      :precision="1"
                      controls-position="right"
                      class="full-width"
                    >
                      <template #append>kg</template>
                    </el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="血型">
                <el-select v-model="healthRecord.bloodType" placeholder="请选择血型" class="full-width">
                  <el-option label="A型" value="A" />
                  <el-option label="B型" value="B" />
                  <el-option label="AB型" value="AB" />
                  <el-option label="O型" value="O" />
                  <el-option label="未知" value="unknown" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="BMI指数">
                <div class="bmi-display">
                  <span class="bmi-value" :class="bmiStatus.class">{{ bmi }}</span>
                  <span class="bmi-status" :class="bmiStatus.class">{{ bmiStatus.text }}</span>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
        
        <!-- 过敏史卡片 -->
        <div class="info-card">
          <div class="card-header">
            <h3><el-icon><Warning /></el-icon>过敏史</h3>
          </div>
          <div class="card-content">
            <el-input
              v-model="healthRecord.allergies"
              type="textarea"
              :rows="4"
              placeholder="请详细描述您的过敏史，包括药物过敏、食物过敏等"
              maxlength="500"
              show-word-limit
            />
          </div>
        </div>
        
        <!-- 既往病史卡片 -->
        <div class="info-card">
          <div class="card-header">
            <h3><el-icon><Document /></el-icon>既往病史</h3>
          </div>
          <div class="card-content">
            <el-input
              v-model="healthRecord.medicalHistory"
              type="textarea"
              :rows="4"
              placeholder="请描述您的既往疾病史、手术史等重要医疗信息"
              maxlength="1000"
              show-word-limit
            />
          </div>
        </div>
        
        <!-- 家族病史卡片 -->
        <div class="info-card">
          <div class="card-header">
            <h3><el-icon><UserFilled /></el-icon>家族病史</h3>
          </div>
          <div class="card-content">
            <el-input
              v-model="healthRecord.familyHistory"
              type="textarea"
              :rows="4"
              placeholder="请描述家族中的遗传性疾病、常见疾病等信息"
              maxlength="500"
              show-word-limit
            />
          </div>
        </div>
        
        <!-- 当前用药卡片 -->
        <div class="info-card">
          <div class="card-header">
            <h3><el-icon><Files /></el-icon>当前用药</h3>
          </div>
          <div class="card-content">
            <el-input
              v-model="healthRecord.currentMedications"
              type="textarea"
              :rows="4"
              placeholder="请列出您目前正在服用的药物，包括药名、剂量、频次等"
              maxlength="500"
              show-word-limit
            />
          </div>
        </div>
        
        <!-- 健康数据趋势卡片 -->
        <div class="info-card chart-card">
          <div class="card-header">
            <h3><el-icon><TrendCharts /></el-icon>健康数据趋势</h3>
            <el-button-group size="small">
              <el-button 
                :type="chartType === 'weight' ? 'primary' : ''"
                @click="chartType = 'weight'"
              >
                体重
              </el-button>
              <el-button 
                :type="chartType === 'bmi' ? 'primary' : ''"
                @click="chartType = 'bmi'"
              >
                BMI
              </el-button>
            </el-button-group>
          </div>
          <div class="card-content">
            <div class="chart-container" ref="chartContainer">
              <!-- 这里可以集成图表库如ECharts -->
              <div class="chart-placeholder">
                <el-icon size="60" color="#c0c4cc"><TrendCharts /></el-icon>
                <p>健康数据图表</p>
                <p class="chart-desc">记录更多数据后将显示趋势图</p>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 健康提醒卡片 -->
        <div class="info-card">
          <div class="card-header">
            <h3><el-icon><Bell /></el-icon>健康提醒</h3>
            <el-button size="small" type="primary" text @click="addReminder">
              <el-icon><Plus /></el-icon>
              添加提醒
            </el-button>
          </div>
          <div class="card-content">
            <div v-if="reminders.length > 0" class="reminder-list">
              <div v-for="(reminder, index) in reminders" :key="index" class="reminder-item">
                <div class="reminder-content">
                  <div class="reminder-title">{{ reminder.title }}</div>
                  <div class="reminder-time">{{ reminder.time }}</div>
                </div>
                <el-button 
                  size="small" 
                  type="danger" 
                  text 
                  @click="removeReminder(index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <div v-else class="empty-reminders">
              <p>暂无健康提醒</p>
              <el-button type="primary" size="small" @click="addReminder">
                添加第一个提醒
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加提醒对话框 -->
    <el-dialog
      v-model="reminderDialogVisible"
      title="添加健康提醒"
      width="400px"
      :before-close="handleCloseReminderDialog"
    >
      <el-form :model="newReminder" label-width="80px">
        <el-form-item label="提醒内容">
          <el-input
            v-model="newReminder.title"
            placeholder="请输入提醒内容"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="提醒时间">
          <el-time-picker
            v-model="newReminder.time"
            format="HH:mm"
            placeholder="选择时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="重复">
          <el-select v-model="newReminder.repeat" placeholder="选择重复方式" style="width: 100%">
            <el-option label="每天" value="daily" />
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
            <el-option label="不重复" value="none" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reminderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddReminder">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  DocumentAdd,
  User,
  Warning,
  Document,
  UserFilled,
  Files,
  TrendCharts,
  Bell,
  Plus,
  Delete
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const saving = ref(false)
const chartType = ref('weight')
const chartContainer = ref()
const reminderDialogVisible = ref(false)

// 健康档案数据
const healthRecord = reactive({ ...userStore.healthRecord })

// 健康提醒数据
const reminders = ref([
  { title: '服用降压药', time: '08:00', repeat: 'daily' },
  { title: '测量血压', time: '18:00', repeat: 'daily' }
])

const newReminder = reactive({
  title: '',
  time: null,
  repeat: 'daily'
})

// 计算BMI
const bmi = computed(() => {
  if (!healthRecord.height || !healthRecord.weight) {
    return '--'
  }
  const heightInM = healthRecord.height / 100
  const bmiValue = healthRecord.weight / (heightInM * heightInM)
  return bmiValue.toFixed(1)
})

// BMI状态
const bmiStatus = computed(() => {
  const bmiValue = parseFloat(bmi.value)
  if (isNaN(bmiValue)) {
    return { text: '请输入身高体重', class: 'normal' }
  }
  
  if (bmiValue < 18.5) {
    return { text: '偏瘦', class: 'underweight' }
  } else if (bmiValue < 24) {
    return { text: '正常', class: 'normal' }
  } else if (bmiValue < 28) {
    return { text: '超重', class: 'overweight' }
  } else {
    return { text: '肥胖', class: 'obese' }
  }
})

// 保存健康档案
const handleSave = async () => {
  saving.value = true
  try {
    const result = await userStore.updateHealthRecord(healthRecord)
    if (result.success) {
      ElMessage.success('健康档案保存成功！')
    } else {
      ElMessage.error(result.message || '保存失败，请稍后重试')
    }
  } catch (error) {
    console.error('保存健康档案失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

// 添加提醒
const addReminder = () => {
  reminderDialogVisible.value = true
}

// 确认添加提醒
const confirmAddReminder = () => {
  if (!newReminder.title || !newReminder.time) {
    ElMessage.warning('请填写完整的提醒信息')
    return
  }
  
  const timeStr = newReminder.time.getHours().toString().padStart(2, '0') + ':' + 
                  newReminder.time.getMinutes().toString().padStart(2, '0')
  
  reminders.value.push({
    title: newReminder.title,
    time: timeStr,
    repeat: newReminder.repeat
  })
  
  // 重置表单
  newReminder.title = ''
  newReminder.time = null
  newReminder.repeat = 'daily'
  
  reminderDialogVisible.value = false
  ElMessage.success('健康提醒添加成功！')
}

// 删除提醒
const removeReminder = (index) => {
  reminders.value.splice(index, 1)
  ElMessage.success('提醒已删除')
}

// 关闭提醒对话框
const handleCloseReminderDialog = () => {
  newReminder.title = ''
  newReminder.time = null
  newReminder.repeat = 'daily'
  reminderDialogVisible.value = false
}

onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.health-record-container {
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #409eff;
}

.header-left h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.health-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.info-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-content {
  padding: 20px;
}

.health-form .full-width {
  width: 100%;
}

.bmi-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

.bmi-value {
  font-size: 24px;
  font-weight: 600;
}

.bmi-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.bmi-value.normal,
.bmi-status.normal {
  color: #67c23a;
}

.bmi-status.normal {
  background: #f0f9ff;
}

.bmi-value.underweight,
.bmi-status.underweight {
  color: #409eff;
}

.bmi-status.underweight {
  background: #ecf5ff;
}

.bmi-value.overweight,
.bmi-status.overweight {
  color: #e6a23c;
}

.bmi-status.overweight {
  background: #fdf6ec;
}

.bmi-value.obese,
.bmi-status.obese {
  color: #f56c6c;
}

.bmi-status.obese {
  background: #fef0f0;
}

.chart-card {
  grid-column: span 2;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder p {
  margin: 10px 0 5px 0;
  font-size: 16px;
  font-weight: 500;
}

.chart-desc {
  font-size: 12px !important;
  color: #c0c4cc !important;
}

.reminder-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reminder-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 3px solid #409eff;
}

.reminder-title {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.reminder-time {
  font-size: 12px;
  color: #7f8c8d;
}

.empty-reminders {
  text-align: center;
  padding: 30px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .health-content {
    padding: 20px 15px;
  }
  
  .content-grid {
    grid-template-columns: 1fr;
  }
  
  .chart-card {
    grid-column: span 1;
  }
  
  .header-content {
    padding: 0 10px;
  }
  
  .header-left h1 {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .card-content {
    padding: 15px;
  }
  
  .card-header {
    padding: 15px;
  }
}
</style>